package com.qf.config;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;

/*
    替代web.xml,在服务器启动时，自动执行一些代码(SPI)
 */
public class WebXml extends AbstractDispatcherServletInitializer {
    /*
        加载springmvc子容器
     */
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext mvcIoc = new AnnotationConfigWebApplicationContext();
        mvcIoc.register(SpringMvcConfig.class);
        return mvcIoc;
    }

    /*
        配置DispatcherServlet的url-pattern
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    /*
        加载spring父容器
     */
    @Override
    protected WebApplicationContext createRootApplicationContext() {
        AnnotationConfigWebApplicationContext ioc = new AnnotationConfigWebApplicationContext();
        ioc.register(SpringConfig.class,SecurityConfig.class);
        return ioc;
    }

    /*
        配置post请求乱码解决过滤器
        专门拦截DispatchServlet的过滤器
     */
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("utf-8");
        filter.setForceEncoding(true);

        return new Filter[]{filter};
    }

}
